package com.tony.blog.api.filter;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: XssHttpServletRequestWrapper
 * @Auther: 皮蛋布丁
 * @Date: 2021/08/03/10:15
 * @Description: XSS过滤处理
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    /**
    * @Description: 未被包装过的HttpServletRequest(特殊场景，需要自己过滤)
    * @Param:
    * @return:
    * @Author: 皮蛋布丁
    * @Date: 2021/8/3 11:37
    */
    HttpServletRequest orgRequest;

    /**
    * @Description: HTML过滤
    * @Param:
    * @return:
    * @Author: 皮蛋布丁
    * @Date: 2021/8/3 11:47
    */
    private final static HTMLFilter htmlFilter = new HTMLFilter();

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        //非json类型，直接返回
        if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))) {
            return super.getInputStream();
        }

        //为空，直接返回
        String json = IOUtils.toString(super.getInputStream(),"utf-8");
        if (StringUtils.isBlank(json)) {
            return super.getInputStream();
        }

        //xss过滤
        json = xssEncode(json);
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(json.getBytes("utf-8"));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return true;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() throws IOException {
                return inputStream.read();
            }
        };
    }

    /**
    * @Description: xssEncode 将容易引起xss漏洞的半角字符直接替换程半角字符
    * @Param: [input]
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    * @Date: 2021/8/3 13:23
    */
    private String xssEncode(String input) {
        return htmlFilter.filter(input);
    }

    /**
    * @Description: getParameter 覆盖getParameter方法，将参数名和参数值都做xss过滤
     *                           如果需要获取最原始的值，则通过super.getParameterValues(name)来获取
     *                           getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
    * @Param: [name]
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    * @Date: 2021/8/3 13:27
    */
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(xssEncode(name));
        if (StringUtils.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] parameters = super.getParameterValues(name);
        if (parameters == null || parameters.length == 0) {
            return null;
        }
        for (int i = 0; i < parameters.length; i++) {
            parameters[i] = xssEncode(parameters[i]);
        }
        return parameters;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String,String[]> map = new LinkedHashMap<>();
        Map<String,String[]> parameters = super.getParameterMap();
        for (String key : parameters.keySet()) {
            String[] values = parameters.get(key);
            for (int i = 0; i < values.length; i++) {
                values[i] = xssEncode(values[i]);
            }
            map.put(key,values);
        }
        return map;
    }

    /**
    * @Description: getHeader 覆盖getHeader方法，将参数名和参数值都做xss过滤
     *                        如果需要获取原始的值，则通过super.getHeaders(name)来获取
     *                        getHeaderNames 也可能需要覆盖
    * @Param: [name]
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    * @Date: 2021/8/3 14:04
    */
    @Override
    public String getHeader(String name) {
        String value = super.getHeader(xssEncode(name));
        if (StringUtils.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }

    /**
    * @Description: getOrgRequest 获取最原始request
    * @Param: []
    * @return: javax.servlet.http.HttpServletRequest
    * @Author: 皮蛋布丁
    * @Date: 2021/8/3 14:07
    */
    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }

    /**
    * @Description: getOrgRequest 获取最原始的reques
    * @Param: [request]
    * @return: javax.servlet.http.HttpServletRequest
    * @Author: 皮蛋布丁
    * @Date: 2021/8/3 14:09
    */
    public static HttpServletRequest getOrgRequest(HttpServletRequest request) {
        if (request instanceof XssHttpServletRequestWrapper) {
            return ((XssHttpServletRequestWrapper) request).getOrgRequest();
        }
        return request;
    }
}
